/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.kj.service;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.jeesite.common.cache.CacheUtils;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.mapper.JsonMapper;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.shiro.cache.K;
import com.jeesite.common.shiro.realms.L;
import com.jeesite.modules.aliyun.msg.AliyunSmsUtils;
import com.jeesite.modules.kj.entity.*;
import lombok.val;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeesite.common.entity.Page;
import com.jeesite.common.service.CrudService;
import com.jeesite.modules.kj.dao.KjMemberDao;

import javax.annotation.Resource;

/**
 * kj_memberService
 * @author hzy
 * @version 2021-07-04
 */
@Service
@Transactional(readOnly=true)
public class KjMemberService extends CrudService<KjMemberDao, KjMember> {
	private static final int LEADER = 80;
	private static final String CACHE_NAME = "smsKeyData";
	private static final String MEMBER_INFO = "memberInfo";

	@Value("${msg.sms.template.changeMobile}")
	private String changeMobileConfig;

	@Resource
	KjMemberJobService kjMemberJobService;
	@Resource
	KjActivityCommentService kjActivityCommentService;
	@Resource
	KjMemberIntegralHistoryService kjMemberIntegralHistoryService;
	@Resource
	KjIntegralAuthService kjIntegralAuthService;
	@Resource
	KjMemberBadgeService kjMemberBadgeService;


	/**
	 * 获取单条数据
	 * @param kjMember
	 * @return
	 */
	@Override
	public KjMember get(KjMember kjMember) {
		return super.get(kjMember);
	}

	/**
	 * 查询分页数据
	 * @param kjMember 查询条件
	 * @return
	 */
	@Override
	public Page<KjMember> findPage(KjMember kjMember) {
		return super.findPage(kjMember);
	}

	/**
	 * 保存数据（插入或更新）
	 * @param kjMember
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(KjMember kjMember) {
		if(kjMember.getId()!=null && !kjMember.getId().equals("")){
			//在修改用户数据的时候同时修改用户报名表里面的数据
			this.editMemberJob(kjMember);
			//修改评论表里面的数据
			this.editActivityComment(kjMember);
			//修改历史记录数据
			this.editMemberIntegralHistory(kjMember);
			//修改服务认证数据
			this.editIntegralAuth(kjMember);
			//修改徽章用户数据
			this.editMemberBadge(kjMember);
		}
		if(kjMember.getIsNewRecord()){
			long count = findCount(new KjMember()) + LEADER;
			kjMember.setFoundationNo(generateEventNo(count + 1));
		}
		super.save(kjMember);
	}

	private void editMemberBadge(KjMember kjMember) {
		new Thread(()->{
			KjMemberBadge badge=new KjMemberBadge();
			badge.setMemberId(kjMember.getId());
			List<KjMemberBadge> list;
			synchronized(this) {
				list =kjMemberBadgeService.findList(badge);
			}
			for(KjMemberBadge badge1: list){
				badge1.setMemberName(kjMember.getName());
				kjMemberBadgeService.save(badge1);
			}
		}).start();
	}

	//修改服务认证数据
	private void editIntegralAuth(KjMember kjMember) {
		new Thread(()->{
			KjIntegralAuth auth=new KjIntegralAuth();
			KjMember member=new KjMember();
			BeanUtils.copyProperties(kjMember,member);
			member.setName(null);
			auth.setKjMember(member);
			List<KjIntegralAuth> list;
			synchronized(this) {
				list =kjIntegralAuthService.findList(auth);
			}
			for(KjIntegralAuth auth1: list){
				auth1.setKjMember(kjMember);
				kjIntegralAuthService.save(auth1);
			}
		}).start();
	}

	//修改历史记录数据
	private void editMemberIntegralHistory(KjMember kjMember) {
		new Thread(()->{
			KjMemberIntegralHistory history=new KjMemberIntegralHistory();
			KjMember member=new KjMember();
			BeanUtils.copyProperties(kjMember,member);
			member.setName(null);
			history.setKjMember(member);
			List<KjMemberIntegralHistory> list;
			synchronized(this) {
				list =kjMemberIntegralHistoryService.findList(history);
			}
			for(KjMemberIntegralHistory history1: list){
				history1.setKjMember(kjMember);
				kjMemberIntegralHistoryService.save(history1);
			}
		}).start();
	}

	//同步修改活动评论
	private void editActivityComment(KjMember kjMember) {
		new Thread(()->{
			KjActivityComment comment=new KjActivityComment();
			KjMember member=new KjMember();
			BeanUtils.copyProperties(kjMember,member);
			member.setName(null);
			comment.setKjMember(member);
			List<KjActivityComment> list;
			synchronized(this) {
				list =kjActivityCommentService.findList(comment);
			}
			for(KjActivityComment activityComment:list){
				activityComment.setKjMember(kjMember);
				kjActivityCommentService.save(activityComment);
			}
		}).start();
	}

	//同步修改活动报名信息
	private void editMemberJob(KjMember kjMember) {
		new Thread(()->{
			KjMemberJob job=new KjMemberJob();
			KjMember member=new KjMember();
			BeanUtils.copyProperties(kjMember,member);
			member.setName(null);
			job.setKjMember(member);
			List<KjMemberJob> list;
			synchronized(this) {
				list = kjMemberJobService.findList(job);
			}
			for(KjMemberJob memberJob:list){
				memberJob.setKjMember(kjMember);
				kjMemberJobService.save(memberJob);
			}
//		kjMemberJobService.findList(job).stream().map(e->{
//			e.setKjMember(kjMember);
//			kjMemberJobService.save(e);
//			return e;
//		});
		}).start();
	}

	/**
	 * 更新状态
	 * @param kjMember
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(KjMember kjMember) {
		super.updateStatus(kjMember);
	}

	/**
	 * 删除数据
	 * @param kjMember
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(KjMember kjMember) {
		super.delete(kjMember);
	}

	//通过Openid获取用户
	public KjMember getFirstMember(KjMember kjMember){
		kjMember.getSqlMap().getWhere().disableAutoAddStatusWhere();
		kjMember.setStatus_in(new String[]{KjMember.STATUS_NORMAL, KjMember.STATUS_FREEZE, KjMember.STATUS_DISABLE});
		List<KjMember> members = findList(kjMember);
		if(members.size() > 0){
			return members.get(0);
		}
		return null;
	}


	//生成编号
	private String generateEventNo(long count){
		DecimalFormat df = new DecimalFormat("00000000");
		String num = df.format(count);
		return num;
	}

	public String getShareNo(KjMember member){
		String totalShareNoKey = "totalShareNo";
		String todayStr = DateUtils.formatDate(new Date(), "yyyyMMdd");
		String memberShareNo = CacheUtils.get(MEMBER_INFO, totalShareNoKey + member.getId(), "");
		if(StringUtils.isBlank(memberShareNo)) {
			int totalShareNo = CacheUtils.get(MEMBER_INFO, totalShareNoKey, 0) + 1;
			DecimalFormat df = new DecimalFormat("000");
			String num = df.format(totalShareNo);
			memberShareNo = todayStr + num;
			CacheUtils.put(MEMBER_INFO, totalShareNoKey, totalShareNo);
			CacheUtils.put(MEMBER_INFO, totalShareNoKey + member.getId(), memberShareNo);
		}
		return memberShareNo;
	}

	public void sendChangeMobileSms(String mobile){
		Map<String, Object> tplData = new HashMap<>();
		String code = generateCode();
		tplData.put("code", code);
		String result = AliyunSmsUtils.sendByTemplate(mobile, changeMobileConfig, JSON.toJSONString(tplData));
		Map<String, Object> map = JsonMapper.fromJson(result, Map.class);
		// 发送成功
		if (ObjectUtils.toInteger(map.get("result")) == 0){
			logger.info("已给" + mobile + "发送修改电话短信，验证码为" + code);
			CacheUtils.put(CACHE_NAME, changeMobileKey(mobile), code, 300L);
		}//			 发送失败
		else{
			throw new ServiceException(result);
		}
	}
	public String getChangeMobileCode(String mobile){
		return CacheUtils.get(CACHE_NAME, changeMobileKey(mobile), "");
	}

	private String changeMobileKey(String mobile){
		return "changeMobile-" + mobile;
	}
	private String generateCode(){
		return StringUtils.getRandomNum(6);
	}
}
